package com.calabar.flume.tcp.websocket.server;

import com.calabar.flume.tcp.server.MyTCPSocketServer;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.List;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("ChannelId" + ctx.channel().id().asLongText());
    }
    
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("用户下线: " + ctx.channel().id().asLongText());
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel().close();
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() + ": " + msg.text());
        while (true){
            List<Float> obj = MyTCPSocketServer.queue.poll();
            if(obj!=null){
                long start = System.currentTimeMillis();
                System.out.println("发送开始时间：" + start);
                ctx.channel().writeAndFlush(new TextWebSocketFrame("来自服务端: " +obj));
                long end = System.currentTimeMillis();
                System.out.println("发送结束时间：" + end);
                System.out.println("发送耗时：" + (end-start));
//                Thread.sleep(1000l);
            }
        }
    }
}